package servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.CartDao;
import dao.CommentDao;
import dao.GoodsDao;
import dao.OrderDao;
import dao.Order_itemDao;
import dao.UserDao;
import entity.Comment;
import entity.Goods;
import entity.Order;
import entity.Order_item;
import entity.User;
import net.sf.json.JSONArray;

@WebServlet("/account")
public class AccountServlet extends HttpServlet{
	public static String filename = null;
	private CartDao cartDao = new CartDao();
	private OrderDao orderDao = new OrderDao();
	private Order_itemDao o_itemDao = new Order_itemDao();
	
	private GoodsDao goodsDao = new GoodsDao();
	private UserDao userDao = new UserDao();
	private CommentDao commentDao = new CommentDao();
	private Goods goods = new Goods();
	private User u = new User();
	public static List<Order> allList = null;//所有的记录		
	DecimalFormat df = new DecimalFormat("######0.00");
	Order order = new Order();
	Order_item o_item = new Order_item();
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doPost(req, resp);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");//防止中文乱码
		
		String act = req.getParameter("act");
		
        // 获取Session中的用户uid
        HttpSession session = req.getSession();
        String ud = (String) session.getAttribute("uid");
        int uid = Integer.parseInt(ud);		
		//找到用户				
		u.setUid(uid);
		
		//用户的历史订单
		try {
			u = userDao.queryById(uid);			
			allList =  orderDao.queryUidAll(u.getUid());
			req.setAttribute("olist", allList);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//用户评论列表
		List<Goods> glist =new ArrayList<Goods>();
		try {
			List<Comment> clist = commentDao.queryByUId(uid);
			for(Comment com: clist) {
				goods.setGid(com.getGid()) ;
				goods =goodsDao.queryById(goods);	
				glist.add(goods);
			}
			req.setAttribute("clist", clist);
			req.setAttribute("glist", glist);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		if(act.equals("0")) { //进入
			req.setAttribute("uid", u.getUid());		
			req.setAttribute("uname", u.getUname());
			req.setAttribute("pwd", u.getPwd());
			req.setAttribute("img", u.getImgurl());
			req.getRequestDispatcher("account.jsp").forward(req, resp);

		}else if(act.equals("1")) {  //修改密码
			String oldpwd =req.getParameter("oldpwd"); 
			String newpwd = req.getParameter("newpwd");
			String repwd = req.getParameter("repwd");
			//比较原密码
			if(u.getPwd().equals(oldpwd) ) {
				//修改新密码
				if(newpwd.equals(repwd)) {
					u.setPwd(newpwd);
					userDao.updateUser(u);
					System.out.println(u);
					System.out.println("修改成功");

				}else {
					System.out.println("二次确认密码有误！");
				}
				
			}else {
				System.out.println("原密码有误！");
			}
			Boolean a = true;
			// 把java数组转化成转化成json对象
			JSONArray jsonArray2 = JSONArray.fromObject(a);
			System.out.println(jsonArray2);
			PrintWriter out = resp.getWriter();
			out.print(jsonArray2); // 输出,返给ajax请求
			
		}else if(act.equals("2")) {  //修改头像
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			factory.setSizeThreshold(1024 * 1024);
			List items = null;
			try {
				items = upload.parseRequest(req);
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					// 根据时间戳创建头像文件
					String ak = item.getName();
					String postFix = ak.substring(ak.lastIndexOf("."));//后缀名
					
					System.out.println(postFix);
					
					filename = System.currentTimeMillis() + postFix;
					filename = u.getUid() + postFix;
					
					//临时文件
					String path =req.getSession().getServletContext().getRealPath("img/comments/");
					System.out.println("临时路径 = " +path);
					photo(path,item);
					req.setAttribute("img", filename);

					//保存图片
					String h = System.getProperty("user.dir").replaceAll("\\\\", "/");
					System.out.println("h = " + h);
					h = h + "/workspace";
					String f =h + req.getContextPath() +"/src/main/webapp/img/comments/";//存储路径								
					System.out.println("保存路径："+f);
					photo(f,item);
					u.setImgurl(filename);
					userDao.updateUser(u);
					System.out.println(u);
					System.out.println("修改成功");
					resp.sendRedirect("account?act=0");
				} else {
					System.out.println(item.getFieldName());
					String value = item.getString();
					value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
					System.out.println(value);
					resp.sendRedirect("account?act=0");
				}
			}
		}else {
			
		}
//		req.getRequestDispatcher("account.jsp").forward(req, resp);
	
	}
	//图片保存
	public void photo(String path,FileItem item) throws IOException{
		String imgsrc = path  + filename;

		// 复制文件
		InputStream is = item.getInputStream();
		FileOutputStream fos = new FileOutputStream(imgsrc);
		byte b[] = new byte[1024 * 1024];
		int length = 0;
		while (-1 != (length = is.read(b))) {
			fos.write(b, 0, length);
		}
		fos.flush();
		fos.close();
	}
	
}
